﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Core.BusinessLayer;
using BSCMFF.Core;
using Telerik.Web.UI;

namespace BSCMFF.Web.Pages.Reporting
{
    /// <summary>
    /// Report - top employees according to PKPIs performance.
    /// </summary>
    /// <remarks></remarks>
    public partial class TopPKPIsEmployees : MultiLanguagePage
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (EvalSelection.PublicSelectedValue != 0)
            {
                PanelRewards.Visible = true;

                BSCEntities context = new BSCEntities();
                Evaluation_Period ep = (from eps in context.Evaluation_Period
                                        where eps.ID == EvalSelection.PublicSelectedValue
                                        select eps).SingleOrDefault();

                if (ep.Reward != true || ep.PKPIs != true)
                {
                    LabelNoPKPIs.Visible = true;
                }
                else
                {
                    LabelNoPKPIs.Visible = false;
                    ShowPKPIsCalculation(ep);
                    FillPKPIsBonusGrid(ep);
                }
            }
        }

        /// <summary>
        /// Fills the PKP is bonus grid.
        /// </summary>
        /// <param name="ep">The ep.</param>
        /// <remarks></remarks>
        private void FillPKPIsBonusGrid(Evaluation_Period ep)
        {
            BSCEntities context = new BSCEntities();

            var data = (from epk in context.Evaluation_PKPIs
                        join ee in context.Evaluation_Evaluator_Employee on epk.EEE_FK equals ee.ID
                        where ee.Evaluation_FK == ep.ID && ee.Evaluated == true
                        group epk by new { ee.Employee_FK } into g
                        join u in context.Users on g.Key.Employee_FK equals u.ID
                        join epp in context.Evaluation_Period on ep.ID equals epp.ID
                        orderby u.ID
                        select new
                        {
                            fullname = u.Firstname + " " + u.Lastname,
                            pkpi = (int)g.Sum(epk => (double)epk.Weight * (epk.Score == null ? 0 : epk.Score)) / 100,

                        }).OrderByDescending(o => o.pkpi).ToList();
            
            int numberOfEvaluatedEmployees = (int)RadNumericTextBoxNumberOfEvaluatedEmployees.Value;
            if (numberOfEvaluatedEmployees != 0)
            {
                double bonusPerEmployee = (double)RadNumericTextBoxCurrentBonusForPKPIs.Value / numberOfEvaluatedEmployees;
                RadNumericTextBoxBonusPerEmployee.Value = bonusPerEmployee;
            }

            List<HelpClasss> hclass = new List<HelpClasss>();
            foreach (var d in data)
            {
                double sigmoid = SigmoidHelper.Sigmoid(d.pkpi, (double)ep.SigmoidA, (double)ep.SigmoidB);

                double bonus = (double)RadNumericTextBoxCurrentBonusForPKPIs.Value * sigmoid / numberOfEvaluatedEmployees / 100;

                HelpClasss hc = new HelpClasss();
                hc.Fullname = d.fullname;
                hc.PKPI = d.pkpi;
                if (d.pkpi == 0 && ep.EndDate > DateTime.Today) //not all employees are evaluated yet
                {
                    hc.Bonus = 0;
                }
                else
                {
                    hc.Bonus = bonus;
                }
                hclass.Add(hc);
                //var nd = new {d.fullname, d.pkpi, bonus};
            }

            RadGridPKPIs.DataSource = hclass;
            RadGridPKPIs.DataBind();

        }

        /// <summary>
        /// Shows the PKPIs calculation.
        /// </summary>
        /// <param name="ep">The evaluation period.</param>
        /// <remarks></remarks>
        private void ShowPKPIsCalculation(Evaluation_Period ep)
        {
            BSCEntities context = new BSCEntities();

            decimal totalBonus = (decimal)ep.TotalBonus;
            //RadNumericTextBoxTotalBonus.Value = (double)totalBonus;
            decimal pkpisBonus = ep.Competencies == false ? totalBonus : totalBonus * (100 - (decimal)ep.BonusSliderValue) / 100;

            RadNumericTextBoxCurrentBonusForPKPIs.Value = (double)pkpisBonus;

            List<int> userIDs = (from eee in context.Evaluation_Evaluator_Employee
                                 where eee.Evaluation_FK == ep.ID
                                 select eee.Employee_FK).Distinct().ToList();
            int numberOfEvaluatedEmployees = 0;
            if (userIDs != null)
            {
                numberOfEvaluatedEmployees = userIDs.Count;
            }
            RadNumericTextBoxNumberOfEvaluatedEmployees.Value = numberOfEvaluatedEmployees;

            if (numberOfEvaluatedEmployees != 0)
            {
                double bonusPerEmployee = (double)RadNumericTextBoxCurrentBonusForPKPIs.Value / numberOfEvaluatedEmployees;
                RadNumericTextBoxBonusPerEmployee.Value = bonusPerEmployee;
            }
        }
        /// <summary>
        /// Handles the ItemDataBound event of the RadGridPKPIs control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Web.UI.GridItemEventArgs"/> instance containing the event data.</param>
        /// <remarks></remarks>
        protected void RadGridPKPIs_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = e.Item as GridDataItem;

                //total += Int32.Parse(((Label)item["LabelBonus"].FindControl("LabelBonus")).Text); //RadNumericTextBoxBonus
                total += (double)((RadNumericTextBox)item["Bonus"].FindControl("RadNumericTextBoxBonus")).Value; //RadNumericTextBoxBonus
            }

            if (e.Item is GridFooterItem)
            {
                GridFooterItem footerItem = e.Item as GridFooterItem;
                ((RadNumericTextBox)footerItem["Bonus"].FindControl("RadNumericTextBoxTotalBonus")).Value = total;
            }
        }
        /// <summary>
        /// Total
        /// </summary>
        double total = 0;
    }


    /// <summary>
    /// Help class for LINQ return set.
    /// </summary>
    /// <remarks></remarks>
    class HelpClasss
    {
        /// <summary>
        /// Gets or sets the fullname.
        /// </summary>
        /// <value>The fullname.</value>
        /// <remarks></remarks>
        public string Fullname { get; set; }
        /// <summary>
        /// Gets or sets the PKPI.
        /// </summary>
        /// <value>The PKPI.</value>
        /// <remarks></remarks>
        public int PKPI { get; set; }
        /// <summary>
        /// Gets or sets the bonus.
        /// </summary>
        /// <value>The bonus.</value>
        /// <remarks></remarks>
        public double Bonus { get; set; }
    }
}